package src.io;

import com.sun.org.apache.bcel.internal.generic.Select;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NIOSelectorServer {
    static Selector selector;
    public static void main(String[] args) throws InterruptedException {
        try {
            ServerSocketChannel serverSocketChannl=ServerSocketChannel.open();
            serverSocketChannl.configureBlocking(false);//连接的非阻塞
            serverSocketChannl.bind(new InetSocketAddress(8082));
            selector=Selector.open();
            serverSocketChannl.register(selector,SelectionKey.OP_ACCEPT);
            while (true){
                selector.select();
                Set<SelectionKey> selectionKeys=selector.selectedKeys();
                Iterator<SelectionKey> iterator =selectionKeys.iterator();
                while (iterator.hasNext()){
                    SelectionKey selectionKey=iterator.next();
                    iterator.remove();
                    if (selectionKey.isAcceptable()){
                        handleAccept(selectionKey);
                    }else if(selectionKey.isReadable()){
                        handleRead(selectionKey);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void handleAccept(SelectionKey selectionKey) {
        ServerSocketChannel serverSocketChannel= (ServerSocketChannel) selectionKey.channel();
        try {
            //到这里一定会有客户端连接的
            SocketChannel socketChannel=serverSocketChannel.accept();
            socketChannel.configureBlocking(false);//IO的非阻塞
            socketChannel.write(ByteBuffer.wrap((String.valueOf(System.currentTimeMillis())+"你好,我是服务端").getBytes()));
            socketChannel.register(selector,SelectionKey.OP_READ);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void handleRead(SelectionKey selectionKey) throws InterruptedException {
        SocketChannel socketChannel= (SocketChannel) selectionKey.channel();
        ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
        try {
            socketChannel.read(byteBuffer);
            System.out.println("收到客户端消息"+new String(byteBuffer.array())+"-----------接受时间:"+System.currentTimeMillis());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
